from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from .models import Wallet, WithdrawRequest
from .serializers import WalletSerializer, WithdrawRequestSerializer
from accounts.models import Technician

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def wallet_detail(request):
    # 获取或创建钱包
    wallet, created = Wallet.objects.get_or_create(user=request.user)
    serializer = WalletSerializer(wallet)
    return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def withdraw_request(request):
    # 检查是否是认证技师
    try:
        technician = request.user.technician_profile
        if not technician.is_verified:
            return Response({'error': '技师未认证'}, status=status.HTTP_403_FORBIDDEN)
    except Technician.DoesNotExist:
        return Response({'error': '您不是认证技师'}, status=status.HTTP_403_FORBIDDEN)
    
    # 获取钱包
    wallet, created = Wallet.objects.get_or_create(user=request.user)
    
    # 检查余额
    amount = request.data.get('amount')
    if float(amount) > float(wallet.balance):
        return Response({'error': '余额不足'}, status=status.HTTP_400_BAD_REQUEST)
    
    serializer = WithdrawRequestSerializer(data=request.data)
    if serializer.is_valid():
        # 创建提现申请
        withdraw = serializer.save(wallet=wallet)
        
        # 冻结金额
        wallet.frozen_amount = float(wallet.frozen_amount) + float(amount)
        wallet.balance = float(wallet.balance) - float(amount)
        wallet.save()
        
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def withdraw_history(request):
    # 获取提现历史
    wallet, created = Wallet.objects.get_or_create(user=request.user)
    withdraw_requests = WithdrawRequest.objects.filter(wallet=wallet).order_by('-created_at')
    
    serializer = WithdrawRequestSerializer(withdraw_requests, many=True)
    return Response(serializer.data)